#include <QTextCodec>
#include <QFileInfo>
#include <QDir>
#include "Utils.h"

namespace Domy {

Utils::Utils()
{

}

Utils::~Utils()
{

}

QColor Utils::getReverseForegroundColor(const QColor &bg_color)
{
    return ((0.299 * bg_color.red() + 0.587 * bg_color.green() + 0.114 * bg_color.blue()) / 255) > 0.5 ? Qt::black : Qt::white;
}

QString Utils::unicodeDecode(const QByteArray &content, const QString &codec_name)
{
    QString rslt;
    if (codec_name.isEmpty()) {
        return rslt;
    }

    QTextCodec *codec = QTextCodec::codecForName(codec_name.toUtf8());
    rslt = codec->toUnicode(content);
    return rslt;
}

QByteArray Utils::unicodeEncode(const QString &text, const QString &codec_name)
{
    QByteArray rslt;
    if (codec_name.isEmpty()) {
        return rslt;
    }

    QTextCodec *codec = QTextCodec::codecForName(codec_name.toUtf8());
    rslt = codec->fromUnicode(text);
    return rslt;
}

QStringList Utils::getAllCodecNames()
{
    QList<QByteArray> codec_names = QTextCodec::availableCodecs();

    QStringList list;
    bool is_system = false, is_utf8 = false, is_gb2312 = false;
    for (const QByteArray &name : codec_names) {

        if (name == "System") {
            is_system = true;
        }
        else if (name == "UTF-8") {
            is_utf8 = true;
        }
        else if (name == "GB2312") {
            is_gb2312 = true;
        }
        else {
            list << name;
        }
    }

    if (is_gb2312) {
        list.push_front("GB2312");
    }

    if (is_utf8) {
        list.push_front("UTF-8");
    }

    if (is_system) {
        list.push_front("System");
    }

    return list;
}

} // namespace
